package cloudPayAdmin.admin.controller.traffic;

import cloudPayAdmin.admin.dbapp.entity.traffic.TTrafficMessage;
import cloudPayAdmin.admin.entity.http.GetAllMessageListResp;
import cloudPayAdmin.admin.service.traffic.TrafficDetectorService;
import cloudPayAdmin.admin.service.traffic.TrafficMessageService;
import cloudPayAdmin.constant.BusiError;
import cloudPayAdmin.util.*;
import cloudPayAdmin.util.pagebean.HqlPageBeanHelper;
import cloudPayAdmin.util.pagebean.HqlParam;
import cloudPayAdmin.util.pagebean.PageBean;
import com.alibaba.fastjson.JSON;
import com.jfinal.kit.HttpKit;
import com.project.m.api.common.biz.resp.BizResp;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/traffic/message")
public class TrafficMessageController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    HqlPageBeanHelper hqlPageBeanHelper;

    @PersistenceContext(unitName = "entityManagerFactory")
    EntityManager entityManager;

    @Autowired
    Environment env;

    @Autowired
    TrafficMessageService trafficMessageService;

    @Autowired
    TrafficDetectorService trafficDetectorService;

    @RequestMapping(value = "/toListPage")
    public String toListPage(HttpServletRequest request, Map<String, Object> model) {
        request.setAttribute("detectorList", trafficDetectorService.findAll());
        return "/traffic/message/traffic-message-list";
    }


    @RequestMapping("/getMessageListData")
    @ResponseBody
    public String getMessageListData(HttpServletRequest request) {
        Map<String, Object> paramMap = WebUtil.getSearchParam(request);
        paramMap = WebUtil.formatDateRange(paramMap, TimeUtil.DATE_PATTERN_NOSEPARTOR);
        System.out.println("paramMap = " + JSON.toJSONString(paramMap));
        // 需要映射的实体类
        HqlParam hqlParam = WebUtil.buildHqlParam(paramMap, TTrafficMessage.class, request);
        PageBean<TTrafficMessage> cloudpayCardPage = hqlPageBeanHelper.findHqlPageBean(entityManager, hqlParam);

        AdminLteDataTableResp<TTrafficMessage> resp = AdminLteUtil.pageBeanToAdminLteDataTableResp(cloudpayCardPage, request);
        System.out.println("resp = " + resp.toAdminLteJsonString(TTrafficMessage.class));
        return resp.toAdminLteJsonString(TTrafficMessage.class);
    }

    @RequestMapping("/getAllMessageListData")
    @ResponseBody
    public String getAllMessageListData(HttpServletRequest request) {
        //logger.info("getAllMessageListData");
        GetAllMessageListResp resp = new GetAllMessageListResp();
        try {
            String bodyString = HttpKit.readData(request);
            //System.out.println("bodyString = " + bodyString);
            Map<String, Object> resultMap = JSON.toJavaObject(JSON.parseObject(bodyString), Map.class);
            //System.out.println("parse = " + resultMap.get("detectorId"));
            Long detectorId = Long.parseLong(String.valueOf(resultMap.get("detectorId")));
            String type = String.valueOf(resultMap.get("type"));

            String startTime = String.valueOf(resultMap.get("startTime"));
            String findStartTime = "";
            String findEndTime = "";
            logger.info("startTime = " + startTime);
            if (StringUtils.isNotBlank(startTime)) {
                String[] values = StringUtils.splitByWholeSeparator(startTime, WebUtil.DATERANGE_SEPARATOR);
                findStartTime = values[0].trim() + " 00:00:00";
                findStartTime = TimeUtil.transferDateFormat(findStartTime, TimeUtil.DEFAULT_DATE_PATTERN, TimeUtil.DATE_PATTERN_NOSEPARTOR);
                findEndTime = values[1].trim() + " 23:59:59";
                findEndTime = TimeUtil.transferDateFormat(findEndTime, TimeUtil.DEFAULT_DATE_PATTERN, TimeUtil.DATE_PATTERN_NOSEPARTOR);
            }

            logger.info("findStartTime = " + findStartTime);
            logger.info("findEndTime = " + findEndTime);

            List<TTrafficMessage> trafficMessageList = trafficMessageService.findByDetectorId(detectorId, true, findStartTime, findEndTime);
            List<Map<String, Object>> drawDataList = new ArrayList<Map<String, Object>>();

            logger.info("trafficMessageList.size() = " + trafficMessageList.size());

            int step = 1;
            if (trafficMessageList.size() > 100) {
                step = trafficMessageList.size() / 100;
            }
            logger.info("step = " + step);

            for (int i = 0; i < trafficMessageList.size(); i = i + step) {
                Map<String, Object> drawData = new HashMap<String, Object>();
                drawData.put("y", TimeUtil.transferDateFormat(trafficMessageList.get(i).getStartTime(), TimeUtil.DATE_PATTERN_NOSEPARTOR, TimeUtil.DEFAULT_DATE_PATTERN));
                if (type.equalsIgnoreCase("1")) {
                    drawData.put("item1", trafficMessageList.get(i).getFlow());
                } else if (type.equalsIgnoreCase("2")) {
                    drawData.put("item1", trafficMessageList.get(i).getSaturation());
                } else if (type.equalsIgnoreCase("3")) {
                    drawData.put("item1", trafficMessageList.get(i).getConvertFlow());
                } else if (type.equalsIgnoreCase("4")) {
                    drawData.put("item1", trafficMessageList.get(i).getGreenTime());
                } else {
                    drawData.put("item1", "");
                }

                drawDataList.add(drawData);
            }
            logger.info("drawDataList = " + JSON.toJSONString(drawDataList));

//            for (TTrafficMessage trafficMessage : trafficMessageList) {
//                if (trafficMessage.getStartTime().endsWith("0000")) {
//                    Map<String, Object> drawData = new HashMap<String, Object>();
//                    drawData.put("y", TimeUtil.transferDateFormat(trafficMessage.getStartTime(), TimeUtil.DATE_PATTERN_NOSEPARTOR, TimeUtil.DEFAULT_DATE_PATTERN));
//                    drawData.put("item1", trafficMessage.getFlow());
//                    drawDataList.add(drawData);
//                }
//            }

            resp.setResult_code(BusiError.ERR_CODE_SUCCESS);
            //resp.setMessages(trafficMessageList);
            resp.setDrawData(drawDataList);
            //logger.info("resp " + resp.getMessages().size());

            return JSON.toJSONString(resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setResult_code(BusiError.ERR_CODE_NET_INNER_POST);
            resp.setError_message(BusiError.ERR_MSG_NET_INNER_POST);
            return JSON.toJSONString(resp);
        }
    }
}
